package at.codebase.web.servlets.api;

import org.json.simple.JSONObject;

import at.codebase.db.dao.EApiAccessDao;
import at.codebase.db.dao.EItemDao;
import at.codebase.db.dao.EMyExternalItemFeedbackDao;
import at.codebase.db.entities.EMyExternalItemFeedback;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters.ParameterDoesNotExistException;
import at.codebase.web.util.URLParameters.ParameterParsingException;
import at.codebase.web.util.servlet.ApiSecureServlet;

public class ItemRatingAPIServlet extends ApiSecureServlet {

	@Override
	protected JSONObject processRequest(RequestInformation requestInfo,
			String authToken) {
		/*
		 * target_user_id: STRING user_name: STRING user_id: STRING rating:
		 * FLOAT (1­5) feedback: STRING feedback_id: STRING
		 */
		try {
			String target_item_id = requestInfo.getParameters().getString(
					"target_item_id");
			String user_name = requestInfo.getParameters().getString(
					"user_name");
			String user_id = requestInfo.getParameters().getString("user_id");
			float rating = (float) requestInfo.getParameters().getDouble(
					"rating");
			String feedbackText = requestInfo.getParameters().getString(
					"feedback");
			EMyExternalItemFeedback feedback = new EMyExternalItemFeedback(
					EApiAccessDao.getPartner(authToken),
					EItemDao.getItemById(new Long(target_item_id)), user_name,
					user_id, rating, feedbackText);
			if (EMyExternalItemFeedbackDao.contains(feedback)) {
				//EMyExternalItemFeedbackDao.save(feedback);
			} else {
				return badRequestResult("Item already rated by this user");
			}
			return successResult();
		} catch (Exception e) {
			return badRequestResult(e.getMessage());
		}
	}

}
